/***************************************************************************//**
 * @file HID/HID_Thread.cpp
 * @author  Marek M. Cel <marekcel@mscsim.org>
 *
 * @section LICENSE
 *
 * Copyright (C) 2014 Marek M. Cel
 *
 * This file is part of MScSim. You can redistribute and modify it under
 * the terms of GNU General Public License as published by the Free Software
 * Foundation; either version 3 of the License, or (at your option) any later
 * version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
 * for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.
 * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 *
 * Further information about the GNU General Public License can also be found
 * on the world wide web at http://www.gnu.org.
 ******************************************************************************/
#ifndef HID_THREAD_CPP
#define HID_THREAD_CPP
#endif

////////////////////////////////////////////////////////////////////////////////

#include <HID/HID_Thread.h>

////////////////////////////////////////////////////////////////////////////////

using namespace std;

////////////////////////////////////////////////////////////////////////////////

HID_Thread::HID_Thread( QObject *parent) :
    QThread ( parent ),

    m_timeoutTimer ( 0 ),
    m_elapsedTimer ( 0 ),

    m_hid ( 0 )
{
    m_hid = new HID_Manager();

    moveToThread( this );
}

////////////////////////////////////////////////////////////////////////////////

HID_Thread::~HID_Thread()
{
    if ( m_timeoutTimer ) delete m_timeoutTimer; m_timeoutTimer = 0;
    if ( m_elapsedTimer ) delete m_elapsedTimer; m_elapsedTimer = 0;

    if ( m_hid ) delete m_hid; m_hid = 0;
}

////////////////////////////////////////////////////////////////////////////////

void HID_Thread::init( WId winId )
{
    m_hid->init( &winId );

    start();

    setPriority( QThread::HighPriority );
}

////////////////////////////////////////////////////////////////////////////////

void HID_Thread::run()
{
    m_timeoutTimer = new QTimer();
    m_elapsedTimer = new QElapsedTimer();

    connect( m_timeoutTimer, SIGNAL(timeout()), this, SLOT(update()) );

    m_timeoutTimer->start( 10 );    // 100 Hz
    m_elapsedTimer->start();

    ///////////////
    QThread::run();
    ///////////////

    disconnect( m_timeoutTimer, SIGNAL(timeout()), 0, 0 );

    m_timeoutTimer->stop();
}

////////////////////////////////////////////////////////////////////////////////

void HID_Thread::update()
{
    double timeStep = (double)m_elapsedTimer->restart() / 1000.0;

    m_hid->update( timeStep );
}
